package com.apes.enquiry.enquiry.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.enquiry.enquiry.model.Enquiry;
import com.apes.enquiry.enquiry.model.EnquiryDataDto;
import com.apes.enquiry.enquiry.model.EnquiryItem;
import com.apes.enquiry.supplier.baturu.service.BaturuInquireService;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.outbox.OutboxSubscriberService;
import com.apes.framework.util.MapUtil;
import com.apes.framework.util.StringUtil;
import com.apes.framework.util.Tools;
import com.apes.scm.masterdata.car.model.CarConfiguration;
import com.apes.scm.masterdata.enumeration.model.BusinessParam;
import com.apes.scm.masterdata.enumeration.repository.BusinessParamRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.masterdata.stock.model.PhyDepot;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import static java.util.stream.Collectors.toList;

/**
 * @Title: BatuRuInquiryService
 * @Author fj
 * @Package com.apes.enquiry.enquiry.service
 * @Date 2023/7/31 15:30
 * @description: 巴图鲁询价
 */
@Service
public class InquiryService extends DomainService {

    @Autowired
    private BaturuInquireService baturuInquireService;

    @Autowired
    private OutboxSubscriberService outboxSubscriberService;

    /**
     * 巴图鲁询价
     * @param dto
     */
    public void inquireData(EnquiryDataDto dto){
        JSONObject inquireData = new JSONObject();
        try {
            JSONObject JS = JSONObject.parseObject(invoke("cm.businessParam.findAllByQueryKey", MapUtil.mapper("queryKey", "baturuSupplier")));
            JSONObject value = JSONObject.parseObject(JS.getString("body"));
            boolean isExistsPurGroup = judgeSendInquiryPurGroup(dto.getEnquiry().getStore(), value.getString("value3"));
            Boolean wantInvoiceFlag = dto.getEnquiry().getBeInvoice();
            JSONObject scopeCar = JSONObject.parseObject(invoke("mdm.supplierBusinessScopeService.externalCallBusinessScopeCar",
                    MapUtil.mapper("supplierId", value.getString("value"), "carlabelId", dto.getEnquiry().getVehicleLabel().getId())));
            boolean scopeCarFlag = scopeCar.getBooleanValue("body");

            Map inquireOtherInfo = checkCarInformation(dto.getEnquiry());
            if (!wantInvoiceFlag && isExistsPurGroup && scopeCarFlag) {
                this.baturuInquireMainData(dto.getEnquiry(), inquireData, inquireOtherInfo, dto.getOrigin());
            }

            dto.getEnquiryItem().forEach(item -> {
                JSONObject excluClassify = JSONObject.parseObject(invoke("mdm.supplierBusinessScopeService.externalCallBusinessScopeClassify",
                        MapUtil.mapper("supplierId", value.getString("value"), "classifyId", item.getClassifyId())));
                boolean excluClassifyFlag = excluClassify.getBooleanValue("body");
                if (!wantInvoiceFlag && isExistsPurGroup && scopeCarFlag && excluClassifyFlag && !item.isProductRule()) {
                    this.baturuInquireData(item, inquireData, dto.getPartyRole());
                }
            });


            if (!wantInvoiceFlag && isExistsPurGroup && scopeCarFlag) {
                SimpleRequest request = new SimpleRequest();
                request.setData(inquireData);
                baturuInquireService.servicePlanToInquire(request);
            }
        } catch (Exception e) {
            outboxSubscriberService.commonSendRequest("local:ServicePlanceService.baturuFailOutbox", "push_baturu_fail_" + dto.getEnquiry().getId(), inquireData);
        }
    }

    /**
     * 封装巴图鲁询价数据
     * @param enquiry
     * @param inquireData
     * @param inquireOtherInfo
     */
    public void baturuInquireMainData(Enquiry enquiry, JSONObject inquireData, Map inquireOtherInfo, String origin) {
        inquireData.put("origin", enquiry.getInnerBusinessKey());
        inquireData.put("originBusinessType", enquiry.getInnerBusinessType());
        inquireData.put("store", origin);

        //根据方案但门店id获取报价组
        JSONObject contact = JSON.parseObject(invoke("cm.deptOfferGroupService.queryContactPersonInfoByDeptId", MapUtil.mapper("deptId", enquiry.getStore())));
        JSONObject body = contact.getJSONObject("body");
        if (ObjectUtils.isEmpty(contact.getJSONObject("body"))){
            throw new RuntimeException("当前门店无报价组，询价无法获取联系人");
        }
        inquireData.put("publishNew", true);
        inquireData.put("contactPerson", body.getString("NAME"));
        inquireData.put("contactPhone", body.getString("MOBILE_NUMBER"));
        inquireData.put("invoiceType",-1);

        JSONObject depts = JSONObject.parseObject(invoke("fn.service.getLocationByDept", MapUtil.mapper("deptId", enquiry.getStore())));
        JSONArray arrays = depts.getJSONArray("body");
        if (!CollectionUtils.isEmpty(arrays)) {
            Location location = JSONObject.parseObject(JSONObject.toJSONString(arrays.get(0)), Location.class);
            JSONObject phyDepotJSON = JSONObject.parseObject(invoke("cm.phyDepot.findOne",MapUtil.mapper("id",location.getPhyDepot().getId())));
            PhyDepot phyDepot = Tools.map(phyDepotJSON.getJSONObject("body"), PhyDepot.class);
            JSONObject receiverAddress = new JSONObject();
            receiverAddress.put("location", phyDepot.getLongitude() +"," + phyDepot.getLatitude());
            receiverAddress.put("address", enquiry.getAddress());
            inquireData.put("inquiryAddress", receiverAddress);
        }
        // 车辆信息
        //获取服务方案"赋能客户车辆扩展信息"
        String servicePlanId = enquiry.getServicePlanId();
        JSONObject servicePlan = null;
        if (servicePlanId.startsWith("DS")){
            //定损方案单
            servicePlan = JSONObject.parseObject(invoke("fn.DServicePlan.findOne",MapUtil.mapper("id",servicePlanId)));
        }else {
            //服务方案单
            servicePlan = JSONObject.parseObject(invoke("fn.servicePlan.findOne",MapUtil.mapper("id",servicePlanId)));
        }
        JSONObject fnCustomerExpand = servicePlan.getJSONObject("body").getJSONObject("fnCustomerExpandTemp");

        JSONArray carInfos = new JSONArray();
        JSONObject carInfo = new JSONObject();
        carInfo.put("vinCode", fnCustomerExpand.getString("vin"));
        carInfo.put("jekunModelCode", fnCustomerExpand.getString("jekunModelCode"));
        carInfo.put("carModelLabel", fnCustomerExpand.getString("carModelLabel"));
        carInfo.put("carLicense", fnCustomerExpand.getString("carLicense"));
        carInfo.put("nameplatePicture", inquireOtherInfo.get("nameplatePicture"));
        carInfo.put("headPicture", inquireOtherInfo.get("headPicture"));
        carInfo.put("trailPicture", inquireOtherInfo.get("trailPicture"));

        carInfos.add(carInfo);
        inquireData.put("carInfos", carInfos);
    }

    /**
     * 转询价 - 巴图鲁询价明细
     * @param item
     * @param inquireData
     * @param platform
     */
    public void baturuInquireData(EnquiryItem item, JSONObject inquireData, PartyRole platform) {
        JSONArray inquiryDetails = new JSONArray();
        JSONObject inquiryDetail = new JSONObject();
        // E01 表示高低配
        if ("E01".equals(item.getOe()) || org.springframework.util.StringUtils.hasText(item.getOe())) {
            String partyName = item.getCategoryName().indexOf("待编译") == -1?item.getCategoryName():item.getSmartEpcPartName();
            inquiryDetail.put("partsName", partyName);
            if (!"E01".equals(item.getOe())) {
                inquiryDetail.put("partsCode", item.getOe());
            }
        } else {
            inquiryDetail.put("partsName", item.getCategoryName());
        }
        inquiryDetail.put("remark", item.getNote());
        inquiryDetail.put("platformId", platform.getId());
        inquiryDetail.put("partsId", item.getId());
        inquiryDetail.put("threePartyDetailCode", item.getId());
        inquiryDetail.put("originProduct", item.getId());
        if ("E01".equals(item.getOe()) && !StringUtils.isEmpty(item.getEpcPicture())) { // E01 高低配，也需要传图片
            inquiryDetail.put("pictures", this.epcPicture(JSONArray.parseArray(item.getEpcPicture())));
        } else if (StringUtils.isEmpty(item.getEpcPicture())) {
            inquiryDetail.put("pictures", "");
        } else {
            inquiryDetail.put("pictures", item.getThisPicture());
        }

        inquiryDetail.put("productRule", item.isProductRule() ? 1 : 0);
        inquiryDetails.add(inquiryDetail);
        if (inquireData.containsKey("inquiryDetails")) {
            JSONArray inquiryDetailsAppend =inquireData.getJSONArray("inquiryDetails");
            inquiryDetailsAppend.addAll(inquiryDetails);
        }else {
            inquireData.put("inquiryDetails", inquiryDetails);
        }
    }

    private JSONArray epcPicture(JSONArray epcPictures) {
        List<BusinessParam> businessParams = getBean(BusinessParamRepository.class).findAllByQueryKey("https");
        String value = businessParams.get(0).getValue();
        JSONArray pictures = new JSONArray();
        epcPictures.forEach(epcP -> {
            JSONObject picO = (JSONObject) epcP;
            pictures.add(value + picO.get("url"));

        });
        return pictures;
    }

    /**
     * 检验车辆信息
     * @param enquiry
     * @return
     */
    public Map checkCarInformation(Enquiry enquiry){
        //数据校验
        judgeCarInfo(enquiry);
        CarConfiguration carConfiguration = enquiry.getVehicleConfig();
        Assert.isTrue(carConfiguration != null,"未找到配置车型信息, 会员扩展信息编码:"+carConfiguration.getId());
        String yjfs = enquiry.getVehicleConfig().getYJFS();
        String modelId = null;
        if (!ObjectUtils.isEmpty(carConfiguration.getCarModel())){
            modelId = carConfiguration.getCarModel().getId();
        }
        Map carPicture = new HashedMap();

        // 非合资 巴图鲁 需要车牌图片
        JSONObject param = new JSONObject();
        param.put("carLicense",enquiry.getCarLicense());
        param.put("vendorCode",enquiry.getVendorCode());
        Object carInfo = this.invoke("fn.customerCar.findOne", param);
        JSONObject resultJson = JSONObject.parseObject(carInfo.toString());

        JSONObject pic1 = resultJson.getJSONObject("pic1");
        JSONObject pic2 = resultJson.getJSONObject("pic2");
        JSONObject pic38 = resultJson.getJSONObject("pic38");
        if (StringUtils.isNotEmpty(yjfs) && "国产".equals(yjfs) && !"CYH0D".equals(modelId)) {
            if (!resultJson.containsKey("pic1") || !resultJson.containsKey("pic38") || !resultJson.containsKey("pic2")) {
                throw new RuntimeException("国产车请在APP上传车头,车尾,铭牌照!!!");
            }
            judgePicture(pic1);
            judgePicture(pic2);
            judgePicture(pic38);
        }
        carPicture.putAll(MapUtil.mapper("headPicture", Objects.isNull(pic1)?"":pic1.get("path"),
                "trailPicture", Objects.isNull(pic2)?"":pic2.get("path"),
                "nameplatePicture", Objects.isNull(pic38)?"":pic38.get("path")));
        return carPicture;
    }

    private boolean judgeSendInquiryPurGroup(String storeId, String purchasingGroupId) {
        JSONObject JS = JSONObject.parseObject(invoke("cm.purchasingGroupService.accordStoreIdFind", MapUtil.mapper("storeId", storeId, "purchasingGroupId", purchasingGroupId)));
        return JS.getBooleanValue("body");
    }

    /**
     * 国产车图片校验
     * @param carPicture
     */
    private void judgePicture(JSONObject carPicture) {
        if (!carPicture.containsKey("path") || StringUtils.isEmpty(carPicture.getString("path")))
            throw new RuntimeException("国产车请在APP上传车头,车尾,铭牌照!!!");
    }

    /**
     * 判断车辆信息
     * @param
     */
    private void judgeCarInfo (Enquiry enquiry) {
        if (enquiry.getVehicleConfig() == null) throw new RuntimeException("该车辆信息不全,请检查车架号码，厂牌，车型，配置车型等信息！！！");
        if (StringUtils.isEmpty(enquiry.getVin())) throw new RuntimeException("该车辆信息不全,请检查车架号码，厂牌，车型，配置车型等信息！！！");
        if (enquiry.getVehicleConfig().getCarLabel() == null) throw new RuntimeException("该车辆信息不全,请检查车架号码，厂牌，车型，配置车型等信息！！！");
        if (enquiry.getVehicleConfig().getCarModel() == null) throw new RuntimeException("该车辆信息不全,请检查车架号码，厂牌，车型，配置车型等信息！！！");
    }

}
